<?php

namespace app\admin\controller;
use app\admin\model\shopro\user\View;
use think\db;
use app\common\controller\Backend;
use base\Wx;

/**
 * 退款订单
 *
 * @icon fa fa-circle-o
 */
class BydOrderTui extends Backend
{
    
    /**
     * BydOrderTui模型对象
     * @var \app\admin\model\BydOrderTui
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\BydOrderTui;
        $this->view->assign("stateList", $this->model->getStateList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 微信退款
     * @param  string   $order_id 	订单ID
     * @return 成功时返回(array类型)，其他抛异常
     */
    public function wxRefund($data) {

        if ( empty($data) )
        {
            return json(['code'=>400,'msg'=>'参数错误']);
        }

        $where = [
            'orderid'          => $data['id'],
            //'state'       => 5,
        ];
        $order = Db::name('BydShopOrder')->where( $where )->find();

        if ( empty($order) )
        {
            return json(['code'=>400,'msg'=>'订单不存在或不符合退款']);
        }
        if($data['prices']>$order['price']){
            return json(['code'=>400,'msg'=>'退款金额不能大于支付金额']);
        }

        $config = [
            'app_id'    => 'wx00e9e5b843259a9d',
            'mch_id'    => '1584376091',
            'key'       => 'TjRUCktaUcR6RQqCksBtwKRY8KwSTC4M',
            'secret'    => 'cce6015196dbba888133f9a3613b18b7',
            'notify'    => 'http://bao.scwushen.com/index.php/api/notify/cg',
        ];

        $obj = new Wx( $config );


        $data = [
            'out_trade_no'  => $order['orderid'],
            'out_refund_no' => "byd".date("YmdHis").round(1000,9999),
            'total_fee'     => $order['price'] * 100,//$order['price'] * 100,
            'refund_fee'    => $data['prices']* 100,
        ];

        $sslCert = substr($_SERVER['DOCUMENT_ROOT'],0,-6) .'/byd-wx-rsakey/bydwxssl_cert.pem';
        $sslKey = substr($_SERVER['DOCUMENT_ROOT'],0,-6) .'/byd-wx-rsakey/bydwxssl_key.pem';

        $ret = $obj->refund( $data, $sslCert, $sslKey );
        //print_r($ret);die;
        if ( $ret['code'] == 200 ) {
            $where = [
                'id'          => $order['id'],
                //'state'       => 5,
            ];
            $save=db('BydShopOrder')->where($where)->update(['state'=>6]);

            if($save){
                return View();
            }
            //退款成功
//            {
//                "code": 200,
//	"msg": "ok",
//	"data": {
//                "return_code": "SUCCESS",
//		"return_msg": "OK",
//		"appid": "wx00e9e5b843259a9d",
//		"mch_id": "1584376091",
//		"nonce_str": "kks5bf6vw8t0xuJn",
//		"sign": "EA66F7744B500744FB875ADBE529C265",
//		"result_code": "SUCCESS",
//		"transaction_id": "4200001311202112308291578368",
//		"out_trade_no": "2021123059829",
//		"out_refund_no": "byd202112301507231000",
//		"refund_id": "50301300442021123015903126950",
//		"refund_channel": [],
//		"refund_fee": "10",
//		"coupon_refund_fee": "0",
//		"total_fee": "100",
//		"cash_fee": "100",
//		"coupon_refund_count": "0",
//		"cash_refund_fee": "10"
//	}
//}
        }
        //退款失败
        return json($ret);



    }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        $temp = explode(",", $row['image']);
        $row['images'] = $temp;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $orderprice=\app\admin\model\BydShopOrder::where('orderid',$row['orderid'])->find();
        if($orderprice){
            $row['price']=$orderprice['price'];
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if($params['state']==1){
               $find=\app\admin\model\BydShopOrder::where('orderid',$params['orderid'])->find();
               if($find['state']==10){
                   $tuisorce=\app\admin\model\BydUser::where('id',$find['user_id'])->setDec('score',$params['prices']);
                   $updat=\app\admin\model\BydShopOrder::where('orderid',$params['orderid'])->update(['state'=>11]);
                   $datas=[
                       'id'=>$params['orderid'],
                       'prices'=>$params['prices']
                   ];
                   $tui=$this->wxRefund($datas);
               }else{
                   $datas=[
                       'id'=>$params['orderid'],
                       'prices'=>$params['prices']
                   ];
                   $tui=$this->wxRefund($datas);
               }

            }
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    /**
     * 检测是否有新退货消息
     */
    public function isHaveNewAfter()
    {
        $cache=\think\Cache::get('tuit');
        if(!empty($cache)){
            $tips = 'aftersale:tips:number';
            //edis = (new Redis())->getRedis();
            $tipsNumber = rand();
            $this->success('获取新退货消息数量成功', null, $tipsNumber);
        }

    }

    /**
     * 已确认新退货消息
     */
    public function handleTui()
    {
        $type = $this->request->post('type');
        $tips = 'aftersale:tips:number';
        $tipsNumber = rand();
        \think\Cache::rm('tuit');
        $this->success('确认新退货消息成功', null, $type);
    }
}
